package com.zhengb.flink.study.datastream.window;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * Created by zhengbo on 2020/1/13.
 */
@Slf4j
public class WindowReduceFunctionDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("10.0.10.36", 9999).flatMap(
                new FlatMapFunction<String, Tuple2<Integer, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<Integer, Integer>> out) throws Exception {
                        for (String s : value.split(",")) {
                            out.collect(new Tuple2<>(1, Integer.parseInt(s)));
                        }
                    }
                }).keyBy(0).timeWindow(Time.seconds(5)).reduce(
                new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return new Tuple2<>(value1.f0, value1.f1 + value2.f1);
                    }
                }).addSink(
                new SinkFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public void invoke(Tuple2<Integer, Integer> value, Context context) throws Exception {

                        log.info("reduce sink data:{}", value);
                    }
                });

        env.execute("WindowReduceFunctionDemo");
    }
}
